#!/bin/sh
html_addr="http://www.nic.edu.cn/RS/ipstat/"
wget -q -O tmp.html "$html_addr"
tmpfile="tmp.txt"
grep -o -P '(([\d]+)|([\d]+.[\d]+)|([\d]+.[\d]+.[\d]+))/\d{1,2}' tmp.html > $tmpfile

printWildCard(){
    sourcefile=$1
    for address in `cat $sourcefile`
    do 
	bits=${address#*/}
	prefix=`expr $bits / 8`
	sufbits=`expr 32 - $bits`
	suffix=`expr $sufbits / 8`
	remains=`expr $sufbits % 8`
	counter=0
	result=${address%/*}
	while [ $counter -lt $suffix ]
	do
	    result=${result}".0"
	    counter=`expr $counter + 1`
	done
	counter=0
	wildcard=
	while [ $counter -lt $prefix ]
	do
	    wildcard=${wildcard}"0."
	    counter=`expr $counter + 1`
	done
	if [ $remains -ne 0 ]
	    then
		num=$(((1<<$remains) - 1))
		if [ $suffix -eq 0 ]
	     	   then 
			wildcard=${wildcard}${num}
		else
			 wildcard=${wildcard}${num}"."
		fi
	fi
	counter=1
	while [ $counter -lt $suffix ]
	do
	    wildcard=${wildcard}"255."
	    counter=`expr $counter + 1`
	done
	if [ $suffix -ne 0 ]
	then
	    wildcard=${wildcard}"255"
	fi
	echo "$result $wildcard"
    done
}

printMaskLength(){
    sourcefile=$1
    for address in `cat $sourcefile`
    do 
	bits=${address#*/}
	prefix=`expr $bits / 8`
	sufbits=`expr 32 - $bits`
	suffix=`expr $sufbits / 8`
	remains=`expr $sufbits % 8`
	counter=0
	result=${address%/*}
	while [ $counter -lt $suffix ]
	do
	    result=${result}".0"
	    counter=`expr $counter + 1`
	done
	echo "$result $bits"
    done
}

if [ $# -gt 1 ]
    then 
	echo "Too many parameters."
	exit 0
fi
if [ $# -eq 1 ] && [ "$1" != "-w" ] 
then 
	echo "wrong parameter"
fi

if [ $# -eq 1 ] && [ "$1" = "-w" ] 
then printWildCard $tmpfile
else
    printMaskLength $tmpfile
fi
rm tmp.html
rm $tmpfile


